<?php

$dir = dirname(__FILE__);

require_once $dir.'/User.php';
require_once $dir.'/Database.php';
require_once $dir.'/Communicator.php';

class Session{
	private $id;
	private $user;
	private $cmm;
	private $db;

	public function __construct($user = null){
		if(session_id() == '') session_start();
		$this->id = session_id();

		if($user != null) $this->user = $user;
		$this->cmm = new Communicator;
		$this->db = new Database;
	}

	public function start(){
		$_SESSION['session_id'] = $this->id;	

		$_SESSION['user_id'] = $this->user->getId();
		$_SESSION['user_token'] = $this->cmm->getToken();

		$me = $this->cmm->getData('me',array('id,name,timezone'));
		$name = $me['name'];
		$timezone = $me['timezone'];
		$id = $me['id'];

		$this->db->execute("SELECT * FROM user WHERE id=$id");
		if($this->db->getNumberOfRows() > 0){
			$query = "UPDATE user SET name='$name', timezone = $timezone WHERE id=$id";
		}else{
			$query = "INSERT INTO user (id,name,timezone) VALUES ($id,'$name',$timezone)";	
		}
		
		$this->setData('timezone',$timezone);
		$this->db->execute($query);
	}

	public function isStarted(){
		if(isset($_SESSION['session_id']) && $_SESSION['session_id'] == $this->id) return true;
		return false;
	}

	public function end(){
		session_destroy();

		$_SESSION['session_id'] = null;

		return $this->cmm->getLogoutUrl();
	}

	public function setUser($user){
		$this->user = $user;
	}

	public function getData($key){
		$key = 'user_'.$key;

		if(isset($_SESSION[$key])) return $_SESSION[$key];
		return false;
	}

	public function setData($key, $value = true){
		$key = 'user_'.$key;
		
		$_SESSION[$key] = $value;
	}

	public function removeData($key){
		$key = 'user_'.$key;

		unset($_SESSION[$key]);
	}

	public function placeLogout(){
		$url = $this->cmm->getLogoutUrl();

		echo "<a class='logoutApp' href='$url'>Sair do aplicativo</a>";
	}

}

?>